package com.flyox.game.militarychess.client.control;

import java.net.InetSocketAddress;

import javax.swing.JOptionPane;

import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.flyox.game.militarychess.CONSTS;
import com.flyox.game.militarychess.client.minaclient.MinaClient;
import com.flyox.game.militarychess.client.minaclient.MinaClientHandler;
import com.flyox.game.militarychess.client.view.ChessFrame;
import com.flyox.game.militarychess.client.view.LoginJDialog;
import com.flyox.game.militarychess.message.ChessPackage;
import com.flyox.game.militarychess.message.Response;

public class MainControl {
	ChessFrame view;
	LoginJDialog loginView;
	
	private NioSocketConnector connector;
	private MinaClient minaClient=null;
	
	public MainControl() {
		connector=new NioSocketConnector();
	}
	
	/**
	 * 链接并登录
	 * @param name
	 * @param pass
	 * @param ip
	 * @param port
	 */
	public void login(String ip,int port){
		if(minaClient==null){
			minaClient = new MinaClient(new MinaClientHandler(MainControl.this));
		}
		if(!minaClient.isConnected()){
			InetSocketAddress address =new  InetSocketAddress(ip,port);
			if (!minaClient.connect(connector, address)) {
				JOptionPane.showMessageDialog(loginView, "Could not connect to " + ip + ". ");
			}
		}
		//登录
		ChessPackage cp=new ChessPackage(CONSTS.CMD_HELLO);
		minaClient.sendRequest(cp);
	}
	
	public void managerLogin(String ip,int port){
		if(minaClient==null){
			minaClient = new MinaClient(new MinaClientHandler(MainControl.this));
		}
		if(!minaClient.isConnected()){
			InetSocketAddress address =new  InetSocketAddress(ip,port);
			if (!minaClient.connect(connector, address)) {
				JOptionPane.showMessageDialog(loginView, "Could not connect to " + ip + ". ");
			}
		}
	}
	
	public void closeSession(){
		minaClient.close();
	}
	/**
	 * 显示登陆结果
	 * @param response
	 */
	public void showLoginRes(Response response){
		loginView.showLoginRes(response);
	}
	
	/**
	 * 发送请求
	 * @param cp
	 */
	public void sendRequest(ChessPackage cp){
		minaClient.sendRequest(cp);
	}

	public void sendMessage(String message){
	}
	public ChessFrame getView() {
		return view;
	}

	public void setView(ChessFrame view) {
		this.view = view;
	}

	public LoginJDialog getLoginView() {
		return loginView;
	}

	public void setLoginView(LoginJDialog loginView) {
		this.loginView = loginView;
	}

	public NioSocketConnector getConnector() {
		return connector;
	}

	public void setConnector(NioSocketConnector connector) {
		this.connector = connector;
	}

	public MinaClient getMinaClient() {
		return minaClient;
	}

	public void setMinaClient(MinaClient minaClient) {
		this.minaClient = minaClient;
	}
	
}
